# -*- coding: utf-8 -*-
# created by Alberthch - 陈航  2021/7/15 21:07
# Description:现在有多个字典或者映射，你想将他们从逻辑上合并为单一的映射后执行某些操作，比如查找值或者检查某些键是否存在

from collections import ChainMap

a = {'x': 1, 'z': 3}
b = {'y': 2, 'z': 4}

# (a) Simple example of combining
# 像普通字典那样使用c
c = ChainMap(a, b)
print(c['x'])  # Outputs 1  (from a)
print(c['y'])  # Outputs 2  (from b)
print(c['z'])  # Outputs 3  (from a)
print("="*20)

# Output some common values
print('len(c):', len(c))
print('c.keys():', list(c.keys()))
print('c.values():', list(c.values()))
print("="*20)

# Modify some values
c['z'] = 10
c['w'] = 40
del c['x']
print("a:", a)

# Example of stacking mappings (like scopes)
values = ChainMap()
values['x'] = 1

# Add a new mapping
values = values.new_child()
values['x'] = 2

# Add a new mapping
values = values.new_child()
values['x'] = 3

print(values)
print(values['x'])

# Discard last mapping
values = values.parents
print(values)
print(values['x'])

# Discard last mapping
values = values.parents
print(values)
print(values['x'])
